<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Joining Conversation...</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: #f5f5f5;
        }
        .container {
            text-align: center;
            padding: 2rem;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .error {
            color: #e74c3c;
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="spinner"></div>
        <div id="status">Loading conversation...</div>
        <div id="error" class="error" style="display: none;"></div>
    </div>

    <script>
        console.log('Join.html loaded, starting join process...');
        
        // Get conversation ID from URL
        const urlParams = new URLSearchParams(window.location.search);
        const conversationId = urlParams.get('conv_id');
        
        async function joinConversation() {
            console.log('joinConversation() called');
            
            if (!conversationId) {
                showError('Invalid join link - no conversation ID provided');
                return;
            }
            
            // Check if user is authenticated
            const authToken = localStorage.getItem('authToken');
            console.log('Auth token exists:', !!authToken);
            
            if (!authToken) {
                // Not authenticated, store pending join and redirect to index for login
                console.log('User not authenticated, redirecting to index.html for login');
                sessionStorage.setItem('pendingJoinConversation', conversationId);
                window.location.href = '/static/index.html';
                return;
            }
            
            try {
                // Call the join API endpoint
                const joinUrl = `/chat/join/${conversationId}`;
                console.log('Calling join API:', joinUrl);
                
                const response = await fetch(joinUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    credentials: 'include'
                });
                
                console.log('Join API response status:', response.status);
                
                if (!response.ok) {
                    if (response.status === 401) {
                        // Auth token expired or invalid
                        localStorage.removeItem('authToken');
                        sessionStorage.setItem('pendingJoinConversation', conversationId);
                        window.location.href = '/static/index.html';
                        return;
                    }
                    throw new Error(`Failed to join conversation: ${response.status}`);
                }
                
                const data = await response.json();
                
                // Store conversation data in localStorage if not already there
                if (data.conversation) {
                    // Get existing conversations from localStorage
                    let conversations = JSON.parse(localStorage.getItem('nlweb_conversations') || '[]');
                    
                    // Check if this conversation already exists
                    const existingIndex = conversations.findIndex(c => c.id === conversationId);
                    
                    if (existingIndex === -1) {
                        // Add new conversation
                        conversations.push({
                            id: conversationId,
                            title: data.conversation.title || 'Shared Conversation',
                            timestamp: Date.now(),
                            sites: data.conversation.sites || [],
                            mode: data.conversation.mode || 'list',
                            participantCount: data.conversation.participant_count || 1
                        });
                        
                        // Save back to localStorage
                        localStorage.setItem('nlweb_conversations', JSON.stringify(conversations));
                    }
                    
                    // Store the messages if provided
                    if (data.conversation.messages && data.conversation.messages.length > 0) {
                        let allMessages = JSON.parse(localStorage.getItem('nlweb_messages') || '[]');
                        
                        // Add messages that don't already exist
                        data.conversation.messages.forEach(msg => {
                            msg.conversation_id = conversationId;
                            const exists = allMessages.some(m => 
                                m.conversation_id === conversationId && 
                                m.message_id === msg.id
                            );
                            if (!exists) {
                                allMessages.push(msg);
                            }
                        });
                        
                        localStorage.setItem('nlweb_messages', JSON.stringify(allMessages));
                    }
                }
                
                // Set the current conversation ID
                localStorage.setItem('currentConversationId', conversationId);
                
                // Redirect to index.html with the conversation ID
                window.location.href = `/static/index.html?conversation=${conversationId}`;
                
            } catch (error) {
                console.error('Error joining conversation:', error);
                showError(error.message);
            }
        }
        
        function showError(message) {
            document.getElementById('status').style.display = 'none';
            document.querySelector('.spinner').style.display = 'none';
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }
        
        // Start the join process when page loads
        joinConversation();
    </script>
</body>
</html>